﻿using System;
using System.Linq;
using System.Reflection;

namespace HCMS.Utils
{
	/// <summary>
	/// <summary>
	/// 实体、DTO 转换工具类
	/// </summary>
	/// </summary>
	public static class EntityConvertUtil
	{
		#region 字段去 NULL 设默认值 FieldsNullConvertDefault
		/// <summary>
		/// 字段去 NULL 设默认值
		/// </summary>
		/// <typeparam name="T">要处理的 Entity、Dto</typeparam>
		/// <param name="entity"></param>
		/// <returns></returns>
		public static T FieldsNullConvertDefault<T>(T entity)
		{
			var result = entity;

			var inputFields = entity.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public);
			var updateFields = result.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public).ToList();
			foreach (var updateFieldsItem in updateFields)
			{
				var inputFieldsItem = inputFields.Where(t => t.Name == updateFieldsItem.Name).FirstOrDefault();
				if (inputFieldsItem != null)
				{
					var value = inputFieldsItem.GetValue(entity);

					// 时间类型 默认值： 当前时间
					if (value != null && inputFieldsItem.PropertyType == typeof(DateTime) && value.ToString() == DateTime.MinValue.ToString())
					{
						value = DateTime.Now;
					}
					else if (value == null)
					{
						if (inputFieldsItem.PropertyType == typeof(string))
						{
							value = "";
						}
						if (inputFieldsItem.PropertyType == typeof(int))
						{
							value = 0;
						}
						if (inputFieldsItem.PropertyType == typeof(float))
						{
							value = 0;
						}
						if (inputFieldsItem.PropertyType == typeof(double))
						{
							value = 0;
						}
						if (inputFieldsItem.PropertyType == typeof(decimal))
						{
							value = 0.0;
						}
						if (inputFieldsItem.PropertyType == typeof(Guid))
						{
							value = Guid.Empty;
						}
					}
					updateFieldsItem.SetValue(result, value);
				}
			}

			return result;
		}
		#endregion

		#region 类型转换 ModelConvert
		/// <summary>
		/// 类型转换
		/// </summary>
		/// <remarks>
		/// 可以将 Entity 转换为 DTO。反之，同理
		/// </remarks>
		/// <typeparam name="resultModel">结果模型</typeparam>
		/// <typeparam name="originModel">原始模型</typeparam>
		/// <param name="inputArg">原始模型参数</param>
		/// <param name="resultArg">结果模型参数</param>
		/// <returns></returns>
		public static resultModel ModelConvert<resultModel, originModel>(originModel inputArg, resultModel resultArg)
		{
			var result = resultArg;

			var inputFields = inputArg.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public);
			var updateFields = result.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public).ToList();
			foreach (var updateFieldsItem in updateFields)
			{
				var inputFieldsItem = inputFields.Where(t => t.Name == updateFieldsItem.Name).FirstOrDefault();
				if (inputFieldsItem != null)
				{
					var value = inputFieldsItem.GetValue(inputArg);
					updateFieldsItem.SetValue(result, value);
				}
			}

			return result;
		}
		#endregion
	}
}
